/*
============================================================================
 Name        : TCPSocketSender.cpp
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : CTCPSocketSender implementation
============================================================================
*/

#include "TCPSocketSender.h"
#include <charconv.h>
#include <EIKENV.H> 
#include <e32des16.h>	
#include <UTF.H> 

// CONSTANTS
const TInt KTimeout = 10;

CTCPSocketSender* CTCPSocketSender::NewL(MObserver& aObserver, RSocket& aSocket)
{
	CTCPSocketSender* self = new(ELeave) CTCPSocketSender(aObserver, aSocket);
	CleanupStack::PushL(self);
	self->ConstructL();
	CleanupStack::Pop();
	return self;
}

CTCPSocketSender::CTCPSocketSender(MObserver& aObserver, RSocket& aSocket) : 
CActive(EPriorityStandard), iObserver(aObserver), iSocket(aSocket)	// Standard priority
{
	CActiveScheduler::Add(this);
}

void CTCPSocketSender::ConstructL()
{
	iTimer = CTCPSocketTimer::NewL(*this);
	iBufferPtr=NULL;
}

CTCPSocketSender::~CTCPSocketSender()
{
	delete iTimer;
	delete iBufferPtr;
	Cancel();
}

//void CTCPSocketSender::ConvUni2Gbk(TDesC& original, TDes8& res) 
//{
//	TInt state = CCnvCharacterSetConverter::KStateDefault;
//
//	CCnvCharacterSetConverter* iConv = CCnvCharacterSetConverter::NewLC();
//
//	if(iConv->PrepareToConvertToOrFromL(KCharacterSetIdentifierGbk,CEikonEnv::Static()->FsSession())!=CCnvCharacterSetConverter::EAvailable)
//	{
//		User::Leave(KErrNotSupported);
//	}
//	iConv->ConvertFromUnicode(res, original, state) ;
//	CleanupStack::PopAndDestroy(iConv);
//}
void CTCPSocketSender::Send(const TDesC8& aMsg)
{
	Cancel();

	TInt size = aMsg.Size();
	delete iBufferPtr;
	iBufferPtr=HBufC8::NewL(size);
	//iBuffer.Copy(pkg);
	iBufferPtr->Des().Copy(aMsg);

	iSocket.Send(iBufferPtr->Des(),0, iStatus);
	SetActive();

	// Start a timeout timer
	iTimer->Start(KTimeout);

	
}

void CTCPSocketSender::DoCancel()
{
	 iSocket.CancelSend();
}

void CTCPSocketSender::RunL()
{
	iTimer->Cancel();	
	iObserver.OnSendL(iBufferPtr->Des(), iStatus.Int());
}

// Functions from CTcpSocketTimer::MTimerObserver
void CTCPSocketSender::OnTimerL(TInt aError)
{	
	TInt err = (aError==KErrNone)?KErrTimedOut:aError;
	iObserver.OnSendL(iBufferPtr->Des(), err);
}
